<?php


namespace App\Common;



use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class Response extends \Illuminate\Http\Response
{
    /**
     * 封装json格式
     * @param int $code
     * @param string $msg
     * @param array $data
     * @return \Illuminate\Http\JsonResponse
     * User: aniu
     * Date: 2020/6/13 10:29 上午
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }
    /**
     * json response
     */
    public function jsonResponse($code, $data = [], $expire = 0)
    {
        if(empty($data)) {
            $data = new \ArrayObject();
        }

        //todo 加入redis服务使用
        if (0 == $code && $expire > 0) {
            $cacheKey = RedisKey::getCacheKey($this->request);
            Redis::setex($cacheKey, $expire, json_encode($data));
        }

        $this->handleNull($data);

        $errMap = config('error');
        return response()->json([
            'code' => $code,
            'message'  => isset($errMap[$code]) ? $errMap[$code] : $errMap[1],
            'data'     => $data
        ])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    }

    public function jsonResponseErr($err, $errMsg = "")
    {
        $errMap = config('error');
        return response()->json([
            'code' => $err,
            'message'  => $errMsg ? $errMsg : (isset($errMap[$err]) ? $errMap[$err] : $errMap[1]),
            'data'     => new \ArrayObject(),
        ])->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    }

    protected function handleNull(&$data)
    {
        if (empty($data)) {
            return $data;
        }
        foreach ($data as $key => &$value) {
            if (is_array($value)) {
                $this->handleNull($value);
            } else {
                if (is_null($value)) {
                    $value = '';
                }
            }
        }
        return $data;
    }
}
